package cn.mily.user.controller;

import cn.mily.basics.utils.JsonResult;
import cn.mily.basics.utils.VerificationCode;
import cn.mily.user.constans.WechatConstans;
import cn.mily.user.domain.User;
import cn.mily.user.domain.dto.RegInfoDto;
import cn.mily.user.service.IWechatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/wechat")
public class WechatController {

    @Autowired
    private IWechatService service;

    /**
     * 微信和用户绑定
     * @param regInfoDto
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public JsonResult bangder(@RequestBody RegInfoDto regInfoDto){
        try {
            return service.bangder(regInfoDto);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(e.getMessage());
        }
    }

    /*拉取二维码*/
    @RequestMapping("/login")
    public String getTwoCode(){
        /*重定向*/
        /**
         * REDIRECT_URI:微信的请求 地址
         * APPID：开发者 id
         * ResURL： 扫完后授权码响应地址
         */
        String uri = WechatConstans.REDIRECT_URI.replace("APPID", WechatConstans.APPID)
                .replace("REDIRECT_URI", WechatConstans.ResURL);
        return "redirect:" + uri;
    }

    /*上面响应的授权码code*/
    @RequestMapping("/callback")
    public String getCode(String code){/* 此处的请求网址没有实质网页   不方便直接处理返回对象  */
        return "redirect:http://localhost:8082/loginWechatCode.html?code="+code;
    }

    /**
     * 根据授权码获取token
     */
    @GetMapping("/{code}")
    @ResponseBody
    public JsonResult getWechatToken(@PathVariable String code){
        try {
            return service.getWechatToken(code);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(e.getMessage());
        }
    }

}
